//
//  PersonalSettingViewController.m
//  HuiKaoClient
//
//  Created by 龚 杰 on 13-2-20.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "PersonalSettingViewController.h"
#import "MainTabBarController.h"
#import "LoginViewController.h"
#import "MyOrderViewController.h"
#import "GOWebViewController.h"
#import "MyCollectionViewController.h"
#import "MyTrainingViewController.h"


@interface PersonalSettingViewController ()

@end

@implementation PersonalSettingViewController

//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}
- (id)init
{
    if (self = [super init]) {
        isLogin = NO;
    }
    return self;
}
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (m_titleBttBarItem.superview  == nil) {
        [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
    }
    if (m_LoginBttBarItem.superview == nil) {
        [self.navigationController.navigationBar addSubview:m_LoginBttBarItem];
    }
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabController.mainselectedIndex =  tMainTabController.selectedIndex;
    if ( tMainTabController.m_UserDic != nil) {
          NSUserDefaults* tUserDef = [NSUserDefaults standardUserDefaults];
        isLogin = YES;
        m_TableView.tableFooterView = m_footView;
        if (m_LoginBttBarItem.superview) {
            [m_LoginBttBarItem removeFromSuperview];
        }
        m_Name.text = [tUserDef objectForKey:@"username"];
        m_Userid = [tUserDef objectForKey:@"user_id"];
        m_headImage._imageRequestURL = [tUserDef objectForKey:@"avatar"];
        m_headImage.m_BoolSetImage = YES;
        [m_headImage customLoadImageFromURL];
    }else{
        isLogin = NO;
         m_TableView.tableFooterView = nil;
    }
    if (m_TableView != nil) {
        [m_TableView reloadData];
    }
 
}
- (void)viewWillDisappear:(BOOL)animated
{
    if (m_LoginBttBarItem.superview) {
        [m_LoginBttBarItem removeFromSuperview];
    }
    if (m_titleBttBarItem.superview) {
        [m_titleBttBarItem removeFromSuperview];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    m_Array1 = [[NSMutableArray alloc] initWithObjects:@"我的订单",@"我的培训班", nil];
    m_Array2 = [[NSMutableArray alloc] initWithObjects:@"个人信息",@"账号设置",@"我的收藏", nil];
    m_Array3 = [[NSMutableArray alloc] initWithObjects:@"邀请好友",@"去给应用打个分，评价一把",@"关于应用", nil];
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        if ([self.navigationController.navigationBar viewWithTag:0x300] == nil) {
            UIImageView* tImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"titleBar.png"]];
            tImgView.tag =0x300;
            tImgView.frame =CGRectMake(0, 0, 320, 44);
            [self.navigationController.navigationBar addSubview:tImgView];
            [tImgView release];
        }
    }
    m_titleBttBarItem = [MainTabBarController setTitle:@"个人"];
    [m_titleBttBarItem retain];
    
    m_LoginBttBarItem = [UIButton buttonWithType:UIButtonTypeCustom];
    m_LoginBttBarItem.frame = CGRectMake(self.navigationController.navigationBar.frame.size.width-55, 7, 50, 30);
    [m_LoginBttBarItem setBackgroundImage:[UIImage imageNamed:@"button_right.png"] forState:UIControlStateNormal];
    [m_LoginBttBarItem setTitle:@"登录" forState:UIControlStateNormal];
    [m_LoginBttBarItem setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    m_LoginBttBarItem.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [m_LoginBttBarItem addTarget:self action:@selector(changeLogin) forControlEvents:UIControlEventTouchUpInside];
    [m_LoginBttBarItem retain];
    
    
    m_TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,self.view.frame.size.width,self.view.frame.size.height-49-44) style:UITableViewStyleGrouped];
    UIView* iview = [[UIView alloc] initWithFrame:m_TableView.frame];
    [iview setBackgroundColor:BACKGROUND_COLOR];
    m_TableView.backgroundView = iview;
    [iview release];
    [m_TableView setDataSource:self];
    [m_TableView setDelegate:self];
    [self.view addSubview:m_TableView];
    
    [self initHeadView];
    [self initFootView];
}
- (void)initHeadView
{
    m_headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 94)];
    [m_headView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"user_background.png"]]];
    
    m_headImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(12, 12, 72, 72)];
    [m_headImage SetUIImage:[UIImage imageNamed:@"avatar.png"]];
    [m_headView addSubview:m_headImage];
    
    UIImageView* m_headMask =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"avatar_mask.png"]];
    m_headMask.frame =CGRectMake(12, 12, 72, 72);
    [m_headView addSubview:m_headMask];
    [m_headMask release];
    
    m_Name = [[UILabel alloc] initWithFrame:CGRectMake(95,22,200,22)];
    m_Name.backgroundColor = [UIColor clearColor];
    m_Name.font = [UIFont boldSystemFontOfSize:20.0f];
    m_Name.textColor = [UIColor whiteColor];
    m_Name.text = @"匿名用户";
    [m_headView addSubview:m_Name];
    
    m_huiyuan= [[UILabel alloc] initWithFrame:CGRectMake(96,50,200,20)];
    m_huiyuan.backgroundColor = [UIColor clearColor];
    m_huiyuan.font = [UIFont boldSystemFontOfSize:14.0f];
    m_huiyuan.textColor = [UIColor whiteColor];
    m_huiyuan.text = @"新手上路";
    [m_headView addSubview:m_huiyuan];
    
    m_TableView.tableHeaderView = m_headView;
}
- (void)initFootView
{
    m_footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320,40)];
    UIButton* ibutton = [UIButton buttonWithType:UIButtonTypeCustom];
    [ibutton setBackgroundImage:[UIImage imageNamed:@"button_red.png"] forState:UIControlStateNormal];
    ibutton.frame = CGRectMake(8, 0, 304,40);
    [ibutton setTitle:@"退出登陆" forState:UIControlStateNormal];
    [ibutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [ibutton addTarget:self action:@selector(changeExit) forControlEvents:UIControlEventTouchUpInside];
    [m_footView addSubview:ibutton];

}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isLogin) {
        if (section == 0) {
            return [m_Array1 count];
        }else if (section == 1) {
            return [m_Array2 count];
        }else if(section == 2){
            return [m_Array3 count];
        }
    }else{
        if (section == 0) {
            return [m_Array1 count];
        } else if (section == 1) {
            return [m_Array3 count];
        }
    }
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  
    if (isLogin) {
        return 3;
    }else{
        return 2;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* tCellstr = @"EXRCell";
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tCellstr];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tCellstr] autorelease];
//        tCell.accessoryType = UITableViewCellAccessoryNone;
//        tCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSUInteger row = indexPath.row;
    NSUInteger section = indexPath.section;

    if (isLogin) {
        if (section == 0) {
            tCell.textLabel.text = (NSString*)[m_Array1 objectAtIndex:row];
        }
        else if(section == 1)
        {
            tCell.textLabel.text = (NSString*)[m_Array2 objectAtIndex:row];
        }
        else{
            tCell.textLabel.text = (NSString*)[m_Array3 objectAtIndex:row];
        }
    }else{
        if (section == 0) {
            tCell.textLabel.text = (NSString*)[m_Array1 objectAtIndex:row];
        }
        else if(section == 1)
        {
            tCell.textLabel.text = (NSString*)[m_Array3 objectAtIndex:row];
        }
    }
    tCell.backgroundColor = [UIColor whiteColor];
    return tCell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView* tSectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
    [tSectionHeaderView setBackgroundColor:[UIColor clearColor]];
    return [tSectionHeaderView autorelease];
}

#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 42;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    NSUInteger section = indexPath.section;
    if (section == 0) {
        if (row == 0) {
            MyOrderViewController* iMyOrder = [[MyOrderViewController alloc] init];
            iMyOrder.hidesBottomBarWhenPushed = YES;
            iMyOrder.navigationItem.hidesBackButton =YES;
            [self.navigationController pushViewController:iMyOrder animated:YES];
            [iMyOrder release];
        }else{
            MyTrainingViewController* iMyTraining = [[MyTrainingViewController alloc] init];
            iMyTraining.hidesBottomBarWhenPushed = YES;
            iMyTraining.navigationItem.hidesBackButton =YES;
            [self.navigationController pushViewController:iMyTraining animated:YES];
            [iMyTraining release];
        }
    }
    if (isLogin) {
        if(section == 1)
        {
            if (row == 0)
            {
                MyInAndPassViewController* iMyInAndPass = [[MyInAndPassViewController alloc] init];
                iMyInAndPass.delegate =self;
                iMyInAndPass.hidesBottomBarWhenPushed = YES;
                iMyInAndPass.navigationItem.hidesBackButton =YES;
                iMyInAndPass.My_IP_type = MYIP_IN;
                [self.navigationController pushViewController:iMyInAndPass animated:YES];
                [iMyInAndPass release];
            }else if(row == 1){
                MyInAndPassViewController* iMyInAndPass = [[MyInAndPassViewController alloc] init];
                 iMyInAndPass.delegate =self;
                iMyInAndPass.hidesBottomBarWhenPushed = YES;
                iMyInAndPass.navigationItem.hidesBackButton =YES;
                iMyInAndPass.My_IP_type = MYIP_PASS;
                [self.navigationController pushViewController:iMyInAndPass animated:YES];
                [iMyInAndPass release];
            }else{
                MyCollectionViewController* iMyCollection = [[MyCollectionViewController alloc] init];
                iMyCollection.hidesBottomBarWhenPushed = YES;
                iMyCollection.navigationItem.hidesBackButton =YES;
                [self.navigationController pushViewController:iMyCollection animated:YES];
                [iMyCollection release];
            }
        }
        else if(section == 2)
        {
            if (row == 0)
            {
                [self SendSMS];
            }
            else if(row == 1)
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/cn/app/fu-zhuang-jin-xiao-cun/id543032455?ls=1&mt=8"]];
            }else{
                GOWebViewController* tWebNewsVC = [[GOWebViewController alloc] init];
                tWebNewsVC.WebURL =@"http://app.gwyscs.com/mapi/about.php";
                NSLog(@"%@",tWebNewsVC.WebURL);
                tWebNewsVC.hidesBottomBarWhenPushed =YES;
                tWebNewsVC.navigationItem.hidesBackButton =YES;
                [self.navigationController pushViewController:tWebNewsVC animated:YES];
                [tWebNewsVC release];
            }
        }
    }else{
       if(section == 1)
        {
            if (row == 0)
            {
                [self SendSMS];

            }
            else if(row == 1)
            {
               [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/cn/app/fu-zhuang-jin-xiao-cun/id543032455?ls=1&mt=8"]];
            }
            else
            {
                GOWebViewController* tWebNewsVC = [[GOWebViewController alloc] init];
                tWebNewsVC.WebURL =@"http://app.gwyscs.com/mapi/about.php";
                NSLog(@"%@",tWebNewsVC.WebURL);
                tWebNewsVC.hidesBottomBarWhenPushed =YES;
                tWebNewsVC.navigationItem.hidesBackButton =YES;
                [self.navigationController pushViewController:tWebNewsVC animated:YES];
                [tWebNewsVC release];
            }
        }
    }
}
#pragma mark MyInAndPassDelegate
- (void)RefreshMyName:(NSString*)name
{
    if (name != nil&&name.length>0) {
        m_Name.text = name;
        [m_TableView reloadData];
    }
}
#pragma mark button
- (void)changeExit
{
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    tMainTabController.m_UserDic = nil;
    if (m_LoginBttBarItem.superview == nil) {
        [self.navigationController.navigationBar addSubview:m_LoginBttBarItem];
    }
    isLogin = NO;
    m_TableView.tableFooterView = nil;
    [m_TableView reloadData];
    m_Name.text = @"匿名用户";
    m_Userid = nil;
    m_headImage._imageRequestURL = nil;
    m_headImage.m_BoolSetImage = NO;
    [m_headImage initSelfImgView:[UIImage imageNamed:@"avatar.png"]];

}
- (void)changeLogin
{
    LoginViewController* tLogin = [[LoginViewController alloc] init];
    tLogin.pushtype = 1;
    tLogin.hidesBottomBarWhenPushed = YES;
    tLogin.navigationItem.hidesBackButton =YES;
    [self.navigationController pushViewController:tLogin animated:YES];
    [tLogin release];
}
#pragma mark SMS
- (void)SendSMS{
    BOOL canSendSMS = [MFMessageComposeViewController canSendText];
	NSLog(@"can send SMS [%d]", canSendSMS);
	if (canSendSMS) {
        
		MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
		picker.messageComposeDelegate = self;
		picker.navigationBar.tintColor = [UIColor blackColor];
		picker.body = @"我下载了一个好用的公务员考试应用，你也一起来看看吧！http://www.gwyscs.com";
//		picker.recipients = [NSArray arrayWithObject:@"186-0123-0123"];
		[self presentModalViewController:picker animated:YES];
		[picker release];
	}	

}
#pragma mark MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
	
	// Notifies users about errors associated with the interface
	switch (result) {
		case MessageComposeResultCancelled:
			//if (DEBUG) NSLog(@"Result: canceled");
			break;
		case MessageComposeResultSent:
			//if (DEBUG) NSLog(@"Result: Sent");
			break;
		case MessageComposeResultFailed:
			//if (DEBUG) NSLog(@"Result: Failed");
			break;
		default:
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    [m_headView release];
    [m_footView release];
    [m_TableView release];
    [m_Name release];
    [m_huiyuan release];
    [m_headImage release];
    [m_Array1 release];
    [m_Array2 release];
    [m_Array3 release];
    [m_LoginBttBarItem release];
    [m_titleBttBarItem release];
    [super dealloc];
}
@end
